package com.shiliuzi.www.util.aliyunUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
public class StoreAliyunUtil {
   public String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    public EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

    public String bucketName = "web-shiliuzi";

    public String filePath= "C:\\file\\error.txt";

    public StoreAliyunUtil() throws ClientException {
    }


    public String storeUtil(MultipartFile file) throws com.aliyuncs.exceptions.ClientException, IOException {
            InputStream inputStream = file.getInputStream();
            String originalFileName = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString() + originalFileName.substring(originalFileName.lastIndexOf("."));


            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, new File(filePath));
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                //拼接url
                String url = endpoint.split("//")[0] + "//" + bucketName + endpoint.split("//")[1] + "/" +fileName;
                ossClient.shutdown();
                return url;
        }
    }

